package com.practice.communication.block;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	
	private static final String CLIENT_DEFAULT_IP = "127.0.0.1";
	
	private static final int CLIENT_DEFAULT_PORT = 8080;
	
	public static void send() {
		send(CLIENT_DEFAULT_IP, CLIENT_DEFAULT_PORT);
	}
	
	public static void send(String ip, int port) {
		BufferedReader in = null;
		PrintWriter out = null;
		Socket socket = null;
		
		try {
			socket = new Socket(ip, port);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
			
			out.println("我是客户端【" + socket.getLocalPort() + "】，向你发送了一条消息!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
			
			if (out != null) {
				out.close();
				out = null;
			}
			
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				socket = null;
			}
		}
	}
	
	public static void receive() {
		receive(CLIENT_DEFAULT_IP, CLIENT_DEFAULT_PORT);
	}
	
	public static void receive(String ip, int port) {
		BufferedReader in = null;
		PrintWriter out = null;
		Socket socket = null;
		
		try {
			socket = new Socket(ip, port);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
			out.println("receive");
			
			String msg = in.readLine();
			System.out.println("我是客户端【" + socket.getLocalPort() + "】，接收到消息：" + msg);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
			
			if (out != null) {
				out.close();
				out = null;
			}
			
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				socket = null;
			}
		}
	}

}
